from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import APIException

from rest_framework.viewsets import GenericViewSet, ModelViewSet, ViewSetMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from utils.common_response import APIResponse
from utils.new_common_response import common_data
from . import models

from .serializer import ProjectModelSerializer, ProjectDetailModelSerializer, ProjectDetailContentModelSerializer, \
    ProjectShoucangModelSerializer, ProjectUpvoteModelSerializer, MyLoveModelSerializer
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin

from utils.private import filters, pagination


class ProjectView(ListModelMixin, GenericViewSet):
    """
    ymq
    产品视图
    """
    queryset = models.Project.objects.filter(is_delete=False, is_show=True).all().order_by('-id')
    serializer_class = ProjectModelSerializer
    filter_backends = [filters.MaxFilterBackend, filters.MinFilterBackend]
    pagination_class = pagination.DataLimitPagination

    def list(self, request, *args, **kwargs):
        """
        重写list
        """
        response = super().list(request, *args, **kwargs)
        old_data = response.data
        new_data = [
            {'id': item['id'], 'title': item['title'], 'num': item['watch_num'], 'comment_num': item['comment_num'],
             'url': item['home_img'], 'style': item['style']} for item in old_data]
        new_data = common_data(new_data)
        response.data = new_data

        return response


class ProjectDetailView(RetrieveModelMixin, GenericViewSet):
    """
    ymq
    详情页
    """
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]
    queryset = models.Project.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = ProjectDetailModelSerializer
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        old_data = response.data
        new_data = common_data(old_data)

        response.data = new_data

        return response


class ProjectDetailGenericViewSet(RetrieveModelMixin, GenericViewSet):
    """
    下单页面，产品详细
    """
    queryset = models.Project.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = ProjectDetailContentModelSerializer

    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        old_data = response.data
        # print(old_data, '<<<<')
        new_data = {'id': old_data['id'], 'image': old_data['home_img'], 'title': old_data['title'],
                    'price': old_data['price'],
                    'detail': old_data['desc'], 'parameter': old_data['product_parameters'],
                    'service': old_data['after_sales']
                    }

        new_data = common_data(new_data)
        response.data = new_data

        return response


class ProjectShoucang(GenericViewSet, CreateModelMixin):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = ProjectShoucangModelSerializer

    def get_serializer_class(self):  # 写在一个视图中，用不同的序列化类
        if self.action == 'upvote':  # 路由后缀为sms_login   用SmsLoginSerializers序列类
            return ProjectUpvoteModelSerializer
        else:
            return super().get_serializer_class()

    @action(methods=["POST"], detail=False)
    def shoucang(self, request, *args, **kwargs):
        id = request.data.get('id')
        # is_shoucang = request.data.get('is_shoucang')
        # print(id,type(is_shoucang))
        # print(is_shoucang)

        ser = self.get_serializer(data=request.data, context={"request": request})
        if ser.is_valid():

            is_shoucang = ser.context.get('is_shoucang')

            return APIResponse(code=100, data='收藏成功', is_shoucang=is_shoucang)
        else:
            raise APIException(ser.errors)

    @action(methods=["POST"], detail=False)
    def upvote(self, request, *args, **kwargs):
        """
        点赞
        """
        serializer = self.get_serializer(data=request.data, context={"request": request})
        serializer.is_valid(raise_exception=True)
        is_upvote = serializer.context.get('is_upvote')
        if is_upvote:
            return APIResponse(code=100, data='点赞成功')
        return APIResponse(code=100, data='您已经点过赞了')


class MyLoveGenericViewSet(ListModelMixin, GenericViewSet):
    """
    我的收藏
    """
    queryset = models.Shoucang.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = MyLoveModelSerializer
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = self.queryset.filter(userinfo_id=self.request.user.id, is_shoucang=True).order_by('-id')
        return queryset

    def list(self, request, *args, **kwargs):
        """
        重写list
        """
        response = super().list(request, *args, **kwargs)
        old_data = response.data
        new_data = common_data(old_data)
        response.data = new_data
        return response
